<template>
  <div class="goodsdetail-container nav-bar-top">
    <van-nav-bar class="nav-bar" title="商品详情" left-arrow @click-left="$router.back()" @click-right="shareShow = true">
      <template #right>
        <van-icon color="#e9b461" name="share-o" size="18" />
      </template>
    </van-nav-bar>
    <van-share-sheet
      v-model="shareShow"
      title="立即分享给好友"
      :options="shareShowList"
      @select="shareShow = false"
    />
    <!-- 轮播图 -->
    <van-swipe v-if="goodsLoading" indicator-color="white" class="goods-swipe" style="height: 376px;">
      <van-swipe-item>
        <div class="goodsLoadingPic">
          <van-loading type="spinner" color="#e9b461"/>
        </div>
      </van-swipe-item>
    </van-swipe>
    <van-swipe v-if="!goodsLoading" :autoplay="3000" indicator-color="white" @change="(index) => {currentPicNum = index}" class="goods-swipe" style="height: 376px;">
      <van-swipe-item v-for="(pic, index) in goodsPicList" :key="index">
        <van-image height="375" width="100%" :src="pic"/>
      </van-swipe-item>
      <template #indicator>
        <div class="custom-indicator" v-if="goodsPicList.length > 1">
          {{ currentPicNum + 1 }}/{{goodsPicList.length}}
        </div>
      </template>
    </van-swipe>
    <!-- 基本信息 -->
    <div v-if="goodsLoading" class="circle-bg goods-info">
      <div class="baseinfo">
        <div class="price skeleton">
          <span class="price-prefix"></span>
          <span class="price-num"></span>
          <!-- <span class="price-tip">优惠价</span> -->
        </div>
        <div class="stock skeleton">
          <span class="origin"></span>
        </div>
      </div>
      <div class="van-multi-ellipsis--l2 goodsTitle skeleton"></div>
    </div>
    <div v-if="!goodsLoading" class="circle-bg goods-info">
      <!-- 普通购买 -->
      <div class="baseinfo" v-if="!$route.query.type">
        <div class="price">
          <span class="price-prefix">¥</span>
          <span class="price-num">{{goodsInfo.price | fentoyuan }}</span>
        </div>
        <div class="stock">
          <span class="origin">库存: {{goodsInfo.stock || 0}} </span>
          <span class="separate">|</span>
          <span class="stock-num">已售: {{goodsInfo.saleCount || 0}} 件</span>
        </div>
      </div>
      <!-- 秒杀 -->
      <div class="baseinfo secKill" v-if="$route.query.type == 'secKill'">
        <div class="price">
          <span class="price-prefix">¥</span>
          <span class="price-num">{{secKillInfo.goodsSecKillPrice | fentoyuan }}</span>
          <span class="price-tip">原价 {{goodsInfo.price | fentoyuan }}</span>
        </div>
        <div class="stock">
          <span class="origin">库存: {{secKillInfo.remainStock || 0}} </span>
        </div>
      </div>
      <div class="van-multi-ellipsis--l2 goodsTitle">
        {{goodsInfo.name}}
      </div>
    </div>
    <!-- 服务 -->
    <div class="circle-bg">
      <van-cell is-link @click="serviceShow = true">
        <div slot="title" class="service">
          <span class="service-title">商品服务</span>
          <span class="service-item"><img src="http://api.7wpp.com/uploads/20200222/57d971eb5984317ee794e531ea0f9207.png"/>极速退款</span>
          <span class="service-item"><img src="http://api.7wpp.com/uploads/20200222/c7e0b30e543aef9e2a801539228fc972.png"/>退货保障</span>
          <span class="service-item"><img src="http://api.7wpp.com/uploads/20200222/73d9b9857972e18b70c4f9aa0cb3cbe1.png"/>7天退换</span>
        </div>
      </van-cell>
      <van-popup v-model="serviceShow" round position="bottom" closeable close-icon="close" :style="{ height: '70%' }" />
      <!-- 规格 -->
      <van-cell v-if="!$route.query.type" class="sku" title="选择规格" is-link @click="skuShow = true"/>
      <van-sku
        v-model="skuShow"
        :sku="skuInfo"
        :goods="skuDefault"
        :goods-id="1"
        :quota="0"
        :quota-used="0"
        :hide-stock="skuInfo.hide_stock"
      />
    </div>
    <!-- 详情 -->
    <van-tabs class="detail circle-bg">
      <van-tab title="商品详情">
        <div v-html="goodsInfo.detail"></div>
      </van-tab>
    </van-tabs>
    <!-- 购买 -->
    <van-goods-action>
      <!-- 普通购买 -->
      <van-goods-action-icon icon="home-o" text="首页" @click="$router.replace('/')"/>
      <van-goods-action-icon @click="handleGoodsFav" :icon="favStatus.icon" text="收藏" :color="favStatus.color"/>
      <van-goods-action-icon icon="cart-o" text="购物车" @click="$router.replace('/cart')" :badge="cartList && cartList.length || ''" />
      <van-goods-action-button v-if="!$route.query.type" type="warning" text="加入购物车" @click="addCart"/>
      <van-goods-action-button v-if="!$route.query.type" type="danger" text="立即购买" @click="buy"/>
      <!-- 秒杀 -->
      <van-goods-action-button :disabled="secKillDisabled" v-if="$route.query.type == 'secKill'" type="warning" :text="secKillText" @click="secKill"/>
    </van-goods-action>
  </div>
</template>

<script>
import { mapState } from 'vuex'

import sysApi from '@/api/sysApi'
import goodsApi from '@/api/goodsApi'
import userApi from '@/api/userApi'
import config from '@/config/config'
import constants from '@/config/constants'

export default {
  name: 'index',
  data () {
    return {
      /* 秒杀状态 */
      secKillDisabled: true,
      secKillText: '秒杀未开始',
      secKillInfo: {},

      /* 收藏状态 */
      favStatus: {
        icon: 'star-o',
        color: '#323233'
      },

      /* 骨架 */
      goodsLoading: true,
      currentPicNum: 0,

      /* 商品分享 */
      shareShow: false,
      shareShowList: config.shareShowList,

      /* 商品服务 */
      serviceShow: false,

      /* 商品sku */
      skuShow: false,
      skuDefault: {
        // 默认商品 sku 缩略图
        picture: 'imgs/goods/1.jpg'
      },
      skuInfo: {
        // 所有sku规格类目与其值的从属关系，比如商品有颜色和尺码两大类规格，颜色下面又有红色和蓝色两个规格值。
        // 可以理解为一个商品可以有多个规格类目，一个规格类目下可以有多个规格值。
        tree: [
          {
            k: '颜色', // skuKeyName：规格类目名称
            k_s: 's1', // skuKeyStr：sku 组合列表（下方 list）中当前类目对应的 key 值，value 值会是从属于当前类目的一个规格值 id
            v: [
              {
                id: '1', // skuValueId：规格值 id
                name: '红色', // skuValueName：规格值名称
                imgUrl: 'imgs/goods/1.jpg', // 规格类目图片，只有第一个规格类目可以定义图片
                previewImgUrl: 'imgs/goods/1.jpg', // 用于预览显示的规格类目图片
              },
              {
                id: '2',
                name: '蓝色',
                imgUrl: 'imgs/goods/2.jpg',
                previewImgUrl: 'imgs/goods/2.jpg',
              }
            ],
            largeImageMode: true, //  是否展示大图模式
          }
        ],
        // 所有 sku 的组合列表，比如红色、M 码为一个 sku 组合，红色、S 码为另一个组合
        list: [
          {
            id: 2259, // skuId
            s1: '1', // 规格类目 k_s 为 s1 的对应规格值 id
            price: 100, // 价格（单位分）
            stock_num: 110 // 当前 sku 组合对应的库存
          },
          {
            id: 2260, // skuId
            s1: '2', // 规格类目 k_s 为 s1 的对应规格值 id
            price: 120, // 价格（单位分）
            stock_num: 90 // 当前 sku 组合对应的库存
          }
        ],
        price: '1.00', // 默认价格（单位元）
        stock_num: 227, // 商品总库存
        collection_id: 2261, // 无规格商品 skuId 取 collection_id，否则取所选 sku 组合对应的 id
        none_sku: false, // 是否无规格商品
        hide_stock: false // 是否隐藏剩余库存
      },

      /* 商品基本信息 */
      goodsInfo: {},
      /* 商品轮播图 */
      goodsPicList: []
    }
  },
  computed: {
    ...mapState(['user','cartList'])
  },
  created () {
    //获取商品详情
    this.getGoodsInfo();
    //获取秒杀详情
    if(this.$route.query.type == 'secKill'){
      this.getSecKillInfo();
    }
  },
  methods: {
    /* 获取商品详情 */
    async getGoodsInfo () {
      const result = await goodsApi.goodsInfo(this.$route.query.id)
      if(result.code == constants.SUCCESS){
        // 基本信息
        this.goodsInfo = result.data;
        // 轮播图
        result.data.resourceList.forEach(resource=>{
          if(resource.type == '0'){
            this.goodsPicList.push(resource.url);
          }
        })
        //隐藏骨架
        setTimeout(() => {
            this.goodsLoading = false;
        }, 100);
        //获取收藏状态
        this.goodsFavStatus();
      }
    },
    /* 获取秒杀详情 */
    async getSecKillInfo () {
      const result = await sysApi.secKillGoodsDetail({goodsId: this.$route.query.id});
      if(result.code == constants.SUCCESS){
        this.secKillInfo = result.data;
        if(result.data.status == '0'){
          this.secKillDisabled = true
          this.secKillText = '秒杀未开始'
        }
        if(result.data.status == '1'){
          this.secKillDisabled = false
          this.secKillText = '立即秒杀'
        }
        if(result.data.status == '2'){
          this.secKillDisabled = true
          this.secKillText = '秒杀已结束'
        }
      }
    },
    /* 获取收藏状态 */
    async goodsFavStatus () {
      if(this.user){
        const result = await userApi.goodsFavStatus({
          goodsId: this.$route.query.id,
          memberId: this.user.id
        });
        if(result.code == constants.SUCCESS){
          if(result.data){
            this.favStatus = {
              icon: 'star',
              color: '#e9b461'
            }
          }else{
            this.favStatus = {
              icon: 'star-o',
              color: '#32323'
            }
          }
        }
      }
    },
    /* 商品收藏 */
    async handleGoodsFav () {
      if(this.user){
        const result = await userApi.handleGoodsFav({
          goodsId: this.$route.query.id,
          memberId: this.user.id,
          favStatus: this.favStatus.icon == 'star' ? '0' : '1'
        });
        if(result.code == constants.SUCCESS){
          this.$toast.success(this.favStatus.icon == 'star' ? '取消收藏' : '添加收藏');
          this.goodsFavStatus();
        }
      }else{
        this.gotoLogin();
      }
    },
    /* 添加购物车 */
    async addCart () {
      if(this.user){
        const result = await userApi.addCart({
          goodsId: this.$route.query.id,
          goodsNum: 1,
          memberId: this.user.id
        });
        if(result.code == constants.SUCCESS){
          this.$store.commit(constants.STORE.UPDATE_CART_LIST);
          this.$toast.success("添加成功");
        }
      }else{
        this.gotoLogin();
      }
    },
    /* 立即购买 */
    async buy () {
      //加入购物车
      if(this.user){
        const result = await userApi.addCart({
          goodsId: this.$route.query.id,
          goodsNum: 1,
          memberId: this.user.id
        });
        if(result.code == constants.SUCCESS){
          //同步出现问题，暂时采用延时解决该bug
          this.$store.commit(constants.STORE.CLEAR_CART_LIST);
          this.$store.commit(constants.STORE.UPDATE_CART_LIST);
          setTimeout(() => {
            this.$store.commit(constants.STORE.UPDATE_CART_CHECKED, {
              id: result.data.id,
              checked: true
            });
            //前往订单预览页面
            this.$router.push("/orderPreview")
          }, 200)
        }
      }else{
        this.gotoLogin();
      }
    },
    /* 秒杀 */
    async secKill () {
      if(this.user){
        this.$toast.loading('正在秒杀...');
        this.secKillDisabled = true;
        //获取秒杀地址
        const urlResult = await sysApi.secKillUrl(this.$route.query.id)
        if(urlResult.code == constants.SUCCESS){
          if(urlResult.data){
            //秒杀下单
            const result = await sysApi.secKill("/secKill"+urlResult.data+"?userId="+this.user.id)
            if(result.code == constants.SUCCESS){
              this.$toast.clear();
              //跳转到支付页面
              this.$router.replace({path: '/orderPreview', query: {goodsId: this.$route.query.id, secKillId: result.data, type: 'secKill'}});
            }else{
              this.secKillDisabled = false;
            }
          }else{
            this.secKillDisabled = false;
          }
        }
      }else{
        this.gotoLogin();
      }
    },
    /* 登录确认 */
    gotoLogin () {
      this.$dialog.confirm({
        title: '',
        message: '还未登录，去登录?'
      })
      .then(() => {
        this.$router.push('/login');
      })
    }
  }
}
</script>

<style lang="scss">
.goodsdetail-container{
  padding-top: 5px;
  margin-bottom: 60px;
  .goodsLoadingPic{
    height: 375px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .goods-swipe{
    margin: 0 auto;
    border-radius: 5px;
    width: calc(100% - (11px) * 2);
    margin-bottom: 10px;
    border: 1px solid #fff;
  }
  .custom-indicator {
    position: absolute;
    right: 12px;
    bottom: 10px;
    padding: 5px 10px;
    font-size: 15px;
    border-radius: 10px;
    color: #fff;
    background: rgba(0, 0, 0, 0.2);
  }
  .goods-info{
    background: url() no-repeat;
    background-size: 100% 100%;
    padding-bottom: 15px;
    padding-top: 0px;
  }
  .secKill{
    .price{
      .price-tip{
        text-decoration: line-through;
      }
    }
  }
  .baseinfo{
    display: flex;
    flex-direction: column;
    padding-bottom: 15px;
    justify-content: center;
    border-radius: 5px;
    .price{
      .price-prefix{
        font-size: 13px;
        color: #fff;
      }
      .price-num{
        font-size: 20px;
        color: #fff;
        font-weight: bold;
        margin: 0 10px 0px 5px;
      }
      .price-tip{
        font-size: 12px;
        color: #fff;
      }
    }
    .price.skeleton{
      height: 34px;
      margin: 5px 0px;
      background: rgba(255,255,255,0.2) !important;
    }
    .stock{
      font-size: 13px;
      color: #fff;
      font-weight: 500;
      .separate{
        margin: 0 5px;
      }
    }
    .stock.skeleton{
      height: 17px;
      background: rgba(255,255,255,0.2) !important;
    }
  }
  .goodsTitle{
    color: #fff;
    font-size: 14px;
  }
  .goodsTitle.skeleton{
    height: 36px;
    background: rgba(255,255,255,0.2) !important;
  }
  .service{
    display: flex;
    justify-content: space-between;
    align-items: center;
    .service-title{
      font-size: 13px;
      margin-right: 10px;
      color: #999;
    }
    .service-item{
      font-size: 13px;
      margin-right: 5px;
      img{
        width: 15px;
        height: 15px;
      }
    }
    span{
      display: flex;
      align-items: center;
      img{
        margin-right: 5px;
        width:20px;
        height: 20px;
      }
    }
  }
  .sku{
    color: #999;
    font-size: 13px;
  }
  .van-goods-action{
    z-index: 2;
    .van-button.van-goods-action-button--warning {
      background: -webkit-linear-gradient(left,#ffd01e,#ff8917) !important;
      background: linear-gradient(to right,#ffd01e,#ff8917) !important;
    }
    .van-button.van-goods-action-button--danger {
      background: -webkit-linear-gradient(left,#ff6034,#ee0a24) !important;
      background: linear-gradient(to right,#ff6034,#ee0a24) !important;
    }
    .van-button.van-goods-action-button--first {
      margin-left: 5px;
      border-top-left-radius: 999px !important;
      border-bottom-left-radius: 999px !important;
    }
    .van-button.van-goods-action-button--last {
      margin-right: 5px;
      border-top-right-radius: 999px !important;
      border-bottom-right-radius: 999px !important;
    }
  }
  .van-sku-actions {
    .van-button.van-button--warning{
      background: -webkit-linear-gradient(left,#ffd01e,#ff8917) !important;
      background: linear-gradient(to right,#ffd01e,#ff8917) !important;
    }
    .van-button:first-of-type {
      border-top-left-radius: 999px !important;
      border-bottom-left-radius: 999px !important;
    }
    .van-button.van-button--danger{
      background: -webkit-linear-gradient(left,#ff6034,#ee0a24) !important;
      background: linear-gradient(to right,#ff6034,#ee0a24) !important;
    }
    .van-button:last-of-type {
      border-top-right-radius: 999px !important;
      border-bottom-right-radius: 999px !important;
    }
  }
  .detail{
    /deep/ .van-tabs__line{
      width: 100%;
      background-color: #f2f2f2;
      height: 1px;
    }
  }
  .van-share-sheet__option{
    flex: 1;
  }
}
</style>
